﻿using System;
using System.Collections.Generic;
using System.Text;
using Tao.OpenGl;

namespace Ommf
{
    public class TileFont : IPrintable
    {
        private Image image;
        private int tileWidth;
        private int tileHeight;
        private Dictionary<char, int> tileDict = new Dictionary<char, int>();

        internal TileFont(Image image, int tileWidth, int tileHeight, string charset)
        {
            this.image = image;
            this.tileWidth = tileWidth;
            this.tileHeight = tileHeight;

            for (int i = 0; i < charset.Length; ++i)
            {
                tileDict.Add(charset[i], i * tileWidth);
            }
        }

        #region IPrintable Members

        public void Print(string text, float x, float y, float angle, float scaleX, float scaleY)
        {
            float tX1 = 0;
            float tY1 = 0;
            float tX2 = (float)tileWidth / (float)image.Width;
            float tY2 = (float)tileHeight / (float)image.Height;
            int offset = 0, drawX = 0, drawY = 0;

            image.Bind();

            Gl.glPushMatrix();

            Gl.glTranslatef(x, y, 0);
            Gl.glRotatef(angle, 0, 0, 1);
            Gl.glScalef(scaleX, scaleY, 1.0f);
            //Gl.glTranslatef(-centerX, -centerY, 0);

            Gl.glBegin(Gl.GL_QUADS);

            for (int i = 0; i < text.Length; ++i)
            {
                if (text[i] != '\n')
                {
                    offset = tileDict[text[i]];
                    tX1 = (float)offset / (float)image.Width;
                    tX2 = (float)(offset + tileWidth) / (float)image.Width;

                    Gl.glTexCoord2f(tX1, tY1); Gl.glVertex3f(drawX, drawY, 0);
                    Gl.glTexCoord2f(tX1, tY2); Gl.glVertex3f(drawX, drawY + tileHeight, 0);
                    Gl.glTexCoord2f(tX2, tY2); Gl.glVertex3f(drawX + tileWidth, drawY + tileHeight, 0);
                    Gl.glTexCoord2f(tX2, tY1); Gl.glVertex3f(drawX + tileWidth, drawY, 0);

                    drawX += tileWidth;
                }
                else
                {
                    drawX = 0;
                    drawY += tileHeight;
                }
            }

            Gl.glEnd();

            Gl.glPopMatrix();
        }

        #endregion
    }
}
